<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        :permission="permissionList"
        v-model="form"
        v-bind="bindVal"
        v-on="onEvent"
        :page.sync="page"
      >
        <template slot="menuLeft">
          <el-button type="primary" size="small" @click.stop="myAdd"
            v-permission="permissionList.addBtn"
            >添 加</el-button
          >
          <el-button type="primary" size="small" @click="delBatchs"
            v-permission="permissionList.delBatchBtn"
            >删除</el-button
          >
          <el-button
            type="primary"
            size="small"
            @click="submitObj"
            v-if="false"
            >提 交</el-button
          >
          <el-button type="primary" size="mini" @click="submitData">加入报表差错</el-button>
        </template>
        <template slot="menu" slot-scope="scope">
          <el-button
            icon="el-icon-edit"
            :size="scope.size"
            :type="scope.type"
            @click.stop="handleEdit(scope.row)"
            v-permission="permissionList.editBtn"
            v-if="scope.row.approvalStatus == 0"
            >编辑</el-button
          >
          <el-button
            icon="el-icon-check"
            :size="scope.size"
            :type="scope.type"
            @click="openPastRecords(scope.row)"
            >查看历史记录</el-button
          >
            <!-- v-if="scope.row.approvalStatus == '0'" -->
          <!-- <el-button
            icon="el-icon-view"
            :size="scope.size"
            :type="scope.type"
            @click.stop="myView(scope.row)"
            >预览</el-button
          > -->
        </template>
      </avue-crud>
    </basic-container>
    <!-- <open-dialog title="添加" :DialogVisible.sync="addVisableDialog">
      <dynamic-crud title="明细" :data="tableDataDetail" :option="tableOptionDetail"
        :rowAdd="rowAdd"></dynamic-crud>
      <avue-form v-model="formAdd" :option="formOption"
        @submit="handleSaveTimely"
        @reset-change="handleResetChange">
      </avue-form>
    </open-dialog> -->
    <el-dialog
      :visible.sync="addVisableDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :fullscreen="addchangeDialogFlag"
      width="60%"
    >
      <div slot="title">
        <div>
          <span class="el-dialog__title">添加</span>
          <div class="avue-crud__dialog__menu">
            <button
              class="el-dialog__headerbtn"
              style="margin-right: 20px"
              @click.stop="addchangeDialog"
            >
              <i class="el-dialog__close el-icon-full-screen"></i>
            </button>
          </div>
          <button type="button" aria-label="Close" class="el-dialog__headerbtn">
            <i class="el-dialog__close el-icon el-icon-close"></i>
          </button>
        </div>
      </div>
      <el-form label-width="60px">
        <avue-form
          v-model="formAdd"
          :option="formOption"
           ref="form" 
        ></avue-form>
        <dynamic-crud
          title="明细"
          :data="tableDataDetail"
          :option="tableOptionDetailAdd"
          :rowAdd="rowadd"
        ></dynamic-crud>
        <!-- <el-form-item label="备注" style="margin-top: 60px; text-algin: center">
          <el-input
            type="textarea"
            v-model="formAdd.remark"
            :rows="5"
          ></el-input>
        </el-form-item> -->
        <div class="bottom-menu">
          <el-button type="primary" @click="save(formAdd)">保存</el-button>
          <el-button type="primary" @click="addVisableDialog = false"
            >取消</el-button
          >
        </div>
      </el-form>
    </el-dialog>

    <el-dialog
      :visible.sync="editVisableDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :fullscreen="editchangeDialogFlag"
      width="60%"
    >
      <div slot="title">
        <div>
          <span class="el-dialog__title">编辑</span>
          <div class="avue-crud__dialog__menu">
            <button
              class="el-dialog__headerbtn"
              style="margin-right: 20px"
              @click.stop="editchangeDialog"
            >
              <i class="el-dialog__close el-icon-full-screen"></i>
            </button>
          </div>
          <button type="button" aria-label="Close" class="el-dialog__headerbtn">
            <i class="el-dialog__close el-icon el-icon-close"></i>
          </button>
        </div>
      </div>
      <el-form label-width="60px">
        <avue-form
          v-model="formAdd.swStInternetTicketEquipment"
          :option="formOption"
          style="margin-bottom: 40px"
        ></avue-form>
        <dynamic-crud
          title="明细"
          :data="tableDataDetail"
          :option="tableOptionDetail"
        ></dynamic-crud>
        <!-- <el-form-item label="备注" style="margin-top: 60px; text-algin: center">
          <el-input
            type="textarea"
            v-model="formAdd.swStInternetTicketEquipment.remark"
            :rows="5"
          ></el-input>
        </el-form-item> -->
        <div class="bottom-menu">
          <el-button type="primary" @click="edit">保存</el-button>
          <el-button type="primary" @click="editVisableDialog = false"
            >取消</el-button
          >
        </div>
      </el-form>
    </el-dialog>

    <el-dialog
      :visible.sync="viewVisableDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :fullscreen="viewchangeDialogFlag"
      width="60%"
    >
      <div slot="title">
        <div>
          <span class="el-dialog__title">预览</span>
          <div class="avue-crud__dialog__menu">
            <button
              class="el-dialog__headerbtn"
              style="margin-right: 20px"
              @click.stop="viewchangeDialog"
            >
              <i class="el-dialog__close el-icon-full-screen"></i>
            </button>
          </div>
          <button type="button" aria-label="Close" class="el-dialog__headerbtn">
            <i class="el-dialog__close el-icon el-icon-close"></i>
          </button>
        </div>
      </div>
      <el-form label-width="40px">
        <avue-form
          v-model="formAdd.swStInternetTicketEquipment"
          :option="formOptionView"
          style="margin-bottom: 40px"
        ></avue-form>
        <div class="header">明细</div>
        <avue-crud
          :data="tableDataDetail"
          :option="tableOptionDetail"
        ></avue-crud>
        <!-- <el-form-item label="备注" style="margin-top: 60px; text-algin: center">
          <el-input
            type="textarea"
            v-model="formAdd.swStInternetTicketEquipment.remark"
            :rows="5"
            disabled="disabled"
          ></el-input>
        </el-form-item> -->
        <div class="bottom-menu">
          <el-button type="primary" @click="viewVisableDialog = false"
            >取消</el-button
          >
        </div>
      </el-form>
    </el-dialog>
      <open-dialog title="历史记录" :DialogVisible.sync="visableDialogRecords">
        <el-form>
          <avue-crud
            :data="tableDataRecords"
            :option="formOptionRecords"
          >
          </avue-crud>
          <div class="bottom-menu">
            <el-button type="primary" @click="visableDialogRecords = false"
              >取消</el-button
            >
          </div>
        </el-form>
      </open-dialog>
      <addReportEditor ref="addReportEditor" @addReportSuccess="getList"></addReportEditor>
  </div>
</template>

<script>
import baseCrud from "@/mixins/base-crud";
import {
  fetchList,
  getObj,
  addObj,
  putObj,
  delObj,
  approvalObj,
  queryPastRecords,
  delBatch
} from "@/api/subwaystm/swstinternetticketequipment/swstinternetticketequipment";
import {
  tableOption,
  formOption,
  formOptionView,
  formOptionRecords
} from "@/const/crud/subwaystm/swstinternetticketequipment/swstinternetticketequipment";
import { tableOptionDetail,tableOptionDetailAdd } from "@/const/crud/subwaystm/swstinternetticketequipment/swstinternetticketequipmentdetails";
import { dateFormat } from "@/util/date";
import { validatenull } from "@/util/validate";
import transitUtil from "@/api/subwayRat/transitUtil";
import addReportEditor from '@/views/stationTiecketManager/xianWngCJXXQR/BBCCGG/BBCCGGSQ/Editor';

export default {
  name: "swstinternetticketequipment",
  mixins: [
    baseCrud(
      "subwaystm/swstinternetticketequipment/swstinternetticketequipment"
    ),
  ],
  components: {
    addReportEditor
  },
  data() {
    return {
      searchForm:{
        approvalStatus: 0
      },
      visableDialogRecords: false,
      tableDataRecords: [],
      formOptionRecords: formOptionRecords,
      tableOptionDetail: tableOptionDetail,
      tableOptionDetailAdd: tableOptionDetailAdd,
      formOption: formOption,
      formOptionView: formOptionView,
      addVisableDialog: false,
      addchangeDialogFlag: false,
      editVisableDialog: false,
      editchangeDialogFlag: false,
      viewVisableDialog: false,
      viewchangeDialogFlag: false,
      formAdd: {
        //swStInternetTicketEquipment: {},
        swStInternetTicketEquipmentDetails: [],
      },
      form: {},
      tableDataDetail: [],
      selectKeys:[]
    };
  },
  props: {
    cashData: {
      type: Array,
      default: function () {
        return [];
      },
    },
    myType: String,
  },
  watch: {
    cashData() {
      this.tableDataDetail = this.cashData;
    },
    tableDataDetail: {
      handler(newValue, oldValue) {
        var totalNumber = 0;
        var totalMoney = 0;
        //   for(var i= 0;i<newValue.length;i++){
        //     newValue[i].totalSaleAmount = 0;
        //     if(newValue[i].ticketAmount && newValue[i].saleNumber){
        //       if(newValue[i].ticketAmount){
        //         newValue[i].totalSaleAmount =  newValue[i].ticketAmount * newValue[i].saleNumber;
        //       }
        //     }
        // }

        for (const item of newValue) {
          totalNumber += item.saleNumber;
          // totalMoney += item.ticketAmount * item.saleNumber;
          totalMoney += item.totalSaleAmount;
        }
        // this.formAdd.swStInternetTicketEquipment.totalNumberSales = totalNumber;
        // this.formAdd.swStInternetTicketEquipment.subtotalTotal = totalMoney;
      },
      immediate: true,
      deep: true,
    },
  },
  created() {
    this.otherVueAction();
    let lineCodes = this.$store.getters.userInfo.lineCode;
    if(lineCodes!=1&&lineCodes!=2&&lineCodes!=3){
      this.$message.error("互联网购票机数据录入只针对1、2、3号线车站，其他线路无需录入互联网购票机数据！");
    }
  },
  computed: {
    permissionList() {
      return {
        addBtn: this.vaildData(
          this.permissions.generator_swstinternetticketequipment_add,
          false
        ),
        delBtn: this.vaildData(
          this.permissions.generator_swstinternetticketequipment_del,
          false
        ),
        delBatchBtn: this.vaildData(
          this.permissions.swstinternetticketequipment_batch_del,
          false
        ),
        editBtn: this.vaildData(
          this.permissions.generator_swstinternetticketequipment_edit,
          false
        ),
      };
    },
  },
  methods: {
    async submitData() {
      if (this.$refs.crud.tableSelect.length < 1) {
        this.$message.error("请选择数据");
        return false;
      }
      if (this.$refs.crud.tableSelect.length != 1) {
        this.$message.error("只能选择一条数据");
        return false;
      }
      let res = false;
      let ress = false;
      for (const table of this.$refs.crud.tableSelect) {
        if (table.approvalStatus != "1") {
          this.$message.error("请选择已提交的数据");
          return false;
        }else{
          if (table.isAddReprotError == "1") {
            res = await this.$confirm('该数据已加入报表差错，是否重新加入？', '提示', {
              confirmButtonText: '是',
              cancelButtonText: '否',
              type: 'warning'
            });
            if (!res) {
              return;
            }else{
              ress = true;
            }
          }
        }
      }
      if(res==false){
        ress = await this.$confirm("是否加入报表差错", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        });
      }
      if (!ress) {
        return;
      }
      this.selectKeys = this.$refs.crud.tableSelect;
      let param={
        dialogTitle: "加入报表差错",
        diffAmountId:this.selectKeys[0].id,
        dataSourceTable:"sw_st_internet_ticket_equipment_details",
        lineCode:this.selectKeys[0].lineCode,
        stationCode:this.selectKeys[0].stationCode,
        reprotTime:this.selectKeys[0].revenueDate,
        reportNameId:13,
        equipmentCode:this.selectKeys[0].equipmentCode,
        settleBeginTime:this.selectKeys[0].startTime,
        settleEndTime:this.selectKeys[0].endTime,
        userCodes:this.selectKeys[0].conductorJobNo,
        showType:3,
        dataSource:1,
        page:this.page
      };
      this.$refs.addReportEditor.others_report_add_call(param);
    },
    async queryPastRecords(row){
      let param={};
      param.id=row.id;
      await queryPastRecords(param)
        .then(res => {
          this.tableDataRecords = res.data.data;
        })
    },
    openPastRecords(row){
      this.tableDataRecords = [];
      this.queryPastRecords(row);
      this.visableDialogRecords=true;
    },
    handleEdit(row){
      this.$refs.crud.rowEdit(row)
    },
    rowadd: function (callback) {
      callback({
        //ticketType: "单程票"
        ticketType: "DCP",
        ticketName: "PTDCP",
      });
    },
    delBatchs: function () {
      if (this.$refs.crud.tableSelect.length < 1) {
        this.$message.error("请选择数据！");
        return false;
      }
      let ids = [];
      for (const table of this.$refs.crud.tableSelect) {
        if (table.approvalStatus != 0) {
          this.$message.error("请选择未提交的数据！");
          return false;
        }
        if (table.reportModifyStatus == "1") {
          this.$message.error("报表修改状态为“是”的情况下，不允许删除数据");
          return false;
        }
        ids.push(table.id);
      }
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        delBatch(ids)
          .then((data) => {
            this.$message.success("删除成功");
            this.getList(this.page);
            done();
          })
          .catch(() => {
            loading();
          });
      });
    },
    submitObj: function () {
      if (this.$refs.crud.tableSelect.length < 1) {
        this.$message.info("请选择要提交的记录");
        return false;
      }
      let ids = [];
      for (const table of this.$refs.crud.tableSelect) {
        if (table.approvalStatus != "0") {
          this.$message.error("请选择未提交的数据");
          return false;
        }
        ids.push(table.id);
      }
      approvalObj({
        ids: ids.join(","),
        status: "1",
      })
        .then((data) => {
          this.$message.success("提交成功");
          this.getList(this.page);
          done();
        })
        .catch(() => {
          loading();
        });
    },
    save(form, done){
      //this.formAdd.swStInternetTicketEquipmentDetails = this.tableDataDetail;
      form.swStInternetTicketEquipmentDetailsList = this.tableDataDetail;
      this.$refs.form.validate(vaild=>{
        if(vaild){
          if (
            this.validatenull(this.formAdd.startTime) ||
            this.validatenull(this.formAdd.endTime)
          ) {
            this.$message.info("开始时间，结束时间为必填项，不能为空！");
            return;
          } else {
            let startDate = Date.parse(
              this.formAdd.startTime
            );
            let endDate = Date.parse(
              this.formAdd.endTime
            );
            if (startDate > endDate) {
              this.$message.warning("开始时间不能大于结束时间");
              return;
            }
          }
          if (form.swStInternetTicketEquipmentDetailsList.length==0) {
              this.$message.warning("请填写明细信息！");
              return;
          }
          for (const item of form.swStInternetTicketEquipmentDetailsList) {
            if (
              this.validatenull(item.ticketType) ||
              this.validatenull(item.equipmentCode) ||
              this.validatenull(item.saleNumber) ||
              this.validatenull(item.totalSaleAmount)
            ) {
              this.$message.info(
                "明细中的票种、设备编号、发售数量、小计金额不能为空！"
              );
              return;
            }
          }
          let now = new Date();
          if (now.getHours() < 6) {
            now.setDate(now.getDate() - 1);
          }
          if(this.formAdd.startTime != dateFormat(now).substring(0, 10) || 
             this.formAdd.endTime != dateFormat(now).substring(0, 10) || 
             this.formAdd.revenueDate != dateFormat(now).substring(0, 10)
          ){
            this.$confirm("开始时间、结束时间或收益日期不是系统默认时间,是否保存？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(() => {
              addObj(form)
                .then((data) => {
                  this.$message.success("添加成功");
                  this.getList(this.page);
                  this.addVisableDialog = false;
                  done();
                })
                .catch(() => {});
            })
          } else {
            addObj(form)
                .then((data) => {
                  this.$message.success("添加成功");
                  this.getList(this.page);
                  this.addVisableDialog = false;
                  done();
                })
                .catch(() => {});
          }
        }
      })
    },
    edit: function () {
      this.formAdd.swStInternetTicketEquipmentDetails = this.tableDataDetail;
      let startDate = Date.parse(
        this.formAdd.startTime
      );
      let endDate = Date.parse(
        this.formAdd.endTime
      );
      if (startDate > endDate) {
        this.$message.warning("开始时间不能大于结束时间");
        return;
      }
      putObj(this.formAdd)
        .then((data) => {
          this.$message.success("修改成功");
          this.getList(this.page);
          this.editVisableDialog = false;
          done();
        })
        .catch(() => {});
    },
    myAdd: function () {
      for (var i in this.formAdd) {
        this.formAdd[i] = null;
      }
      let now = new Date();
      if (now.getHours() < 6) {
        now.setDate(now.getDate() - 1);
      }
      this.formAdd.startTime = dateFormat(now).substr(0, 10);
      this.formAdd.endTime = dateFormat(now).substr(0, 10);
      this.formAdd.revenueDate = dateFormat(now).substr(0, 10);
      this.tableDataDetail = [];
      this.addVisableDialog = true;
    },
    myView: function (row) {
      getObj(row.id)
        .then((response) => {
          let res = response.data.data;
          this.tableDataDetail = res.swStInternetTicketEquipmentDetails;
          this.formAdd.swStInternetTicketEquipment =
            res.swStInternetTicketEquipment;
        })
        .then(() => {
          this.viewVisableDialog = true;
        });
    },
    myEdit: function (row) {
      getObj(row.id)
        .then((response) => {
          let res = response.data.data;
          this.tableDataDetail = res.swStInternetTicketEquipmentDetails;
          for (const item of this.tableDataDetail) {
            item.$cellEdit = true;
          }
          this.formAdd.swStInternetTicketEquipment =
            res.swStInternetTicketEquipment;
        })
        .then(() => {
          this.editVisableDialog = true;
        });
    },
    addchangeDialog: function () {
      if (this.addchangeDialogFlag) {
        this.addchangeDialogFlag = false;
      } else {
        this.addchangeDialogFlag = true;
      }
    },
    editchangeDialog: function () {
      if (this.editchangeDialogFlag) {
        this.editchangeDialogFlag = false;
      } else {
        this.editchangeDialogFlag = true;
      }
    },
    viewchangeDialog: function () {
      if (this.viewchangeDialogFlag) {
        this.viewchangeDialogFlag = false;
      } else {
        this.viewchangeDialogFlag = true;
      }
    },
    otherVueAction(){
      transitUtil.$on('updateReport_call_13',(param)=>{
        let p=param;
        fetchList(p).then(response => {
          this.tableData = response.data.data.records;
          this.page.total = response.data.data.total;
          this.tableLoading = false;
          this.tableLoading = false;
        })
      });
    }
  },
};
</script>
<style lang="scss" scoped>
.header {
  margin: 0 auto;
  width: 99%;
  padding: 5px 10px;
  border: 1px solid #e4e4e4;
  border-bottom: none;
  background-color: #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.bottom-menu {
  margin-top: 48px;
  text-align: center;
}
</style>
